#include "student.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct _Students
{
    int length;
    Student data[MAX_PERSONS_LENGTH];
} Students;

Students *ALL_STUDENTS = NULL;

void Students_Init()
{
    if (ALL_STUDENTS != NULL)
    {
        return;
    }
    ALL_STUDENTS = malloc(sizeof(Students));
    memset(ALL_STUDENTS, 0, sizeof(Students));
}

static uint8_t Student_Introduce(PersonId *selfId, char *result)
{
    if (selfId->id >= MAX_STUDENTS_LENGTH || selfId->typeId != STUDENT_TYPE)
    {
        return 255;
    }
    Student *self = &(ALL_STUDENTS->data[selfId->id]);

    snprintf(result, MAX_INTRODUCE_LENGTH,
             "My name is %s. I am %d years old. I am a student of class %d.",
             self->name, self->age, self->klass);

    return FUNCTION_SUCCESS_CODE;
};


PersonId Student_Create(uint8_t age, char *name, uint8_t klass)
{
     if (ALL_STUDENTS->length >= MAX_STUDENTS_LENGTH)
    {
        PersonId result = {.id = 255, .typeId = STUDENT_TYPE, .Introduce = NULL};
        return result;
    }

    Student *selfObject = &ALL_STUDENTS->data[ALL_STUDENTS->length++];
    selfObject->age = age;
    snprintf(selfObject->name, MAX_NAME_LENGTH, "%s", name);
    selfObject->klass = klass;

    PersonId result = {
        .id = ALL_STUDENTS->length - 1,
        .typeId = STUDENT_TYPE,
        .Introduce = Student_Introduce };
    return result;
}


uint8_t GetStudent(PersonId *selfId, Student *result)
{
    if (selfId->id >= MAX_STUDENTS_LENGTH)
    {
        return 255;
    }
    Student *target = &(ALL_STUDENTS->data[selfId->id]); 
    result->age = target->age;
    snprintf(result->name, MAX_NAME_LENGTH, "%s", target->name);
    result->klass = target->klass;
    return ALL_STUDENTS->length-1;
}
